<?php // Database.php

class Database {
	private static $db;

	public static function connect() {
		if (!self::$db) {
			$env = json_decode(file_get_contents("/home/dotcloud/environment.json"), true);
			$host = ''; $port = ''; $pwd = '';
			
			$host = $env["DOTCLOUD_REDIS_REDIS_HOST"];
			$port = $env["DOTCLOUD_REDIS_REDIS_PORT"];
			$pwd =  $env["DOTCLOUD_REDIS_REDIS_PASSWORD"];
						
			self::$db = new Redis();
			try {
				self::$db->connect($host, $port);
				self::$db->auth($pwd);
			} catch (RedisException $e) {
				die("Error connecting to the database: \n". print_r($e, true)."</pre><br/>");
			}
		} 

		return self::$db;
	}
	
	public static function disconnect() {
		self::$db = null;
	}
	
	public static function insert($obj) {
		Database::connect();

		$tableKey = $obj->tableKey;
		$tableid = $obj->$tableKey;
		$key = $obj->dbTable . ':' . $tableid;
		
		if ($obj->keyType == 'hash') {
			foreach ($obj->getColumns() as $col) {
				$result = false;
				$val = $obj->$col;
				$result = self::$db->hSet($key, $col, $val);
				if ($result === false) die("Error inserting data...\n");
			}

		} else if ($obj->keyType == 'string') {
			$result = self::$db->set($key, $obj->value);
			if ($result === false) die("Error inserting data...\n");

		} else if ($obj->keyType == 'set') {
			// This will add the members to the set
			if (!is_array($obj->members)) $obj->members = array($obj->members);
			foreach ($obj->members as $m) {
				self::$db->sadd($key, $m);
			}

		} else if ($obj->keyType == 'list') {
			if (!is_array($obj->members)) $obj->members = array($obj->members);
			foreach ($obj->members as $m) {
				self::$db->rpush($key, $m);
			}

		}
		
		// If the expire property is set, set a timeout on the key
		// Note that this timeout will be RESET after any change to the data - unlike the standard redis behavior
		if (!Util::isNullOrEmpty($obj->expire)) {
			self::$db->expire($key, $obj->expire);
		}
		
		return true;
	}
	
	public static function update($obj) {
		return self::insert($obj);
	}
}
?>
